home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / std / c++ / 916 < prev    next >
Encoding:
Internet Message Format  |  1996-08-06  |  2.1 KB

  1. From: gregor@netcom.com (Greg Colvin)
  2. Message-ID: <gregorDp23ts.Axt@netcom.com>
  3. X-Original-Date: Sat, 30 Mar 1996 01:22:40 GMT
  4. Path: in1.uu.net!bounce-back
  5. Date: 30 Mar 96 06:08:11 GMT
  6. Approved: fjh@cs.mu.oz.au
  7. Newsgroups: comp.std.c++
  8. Subject: sample auto_ptr template
  9. Organization: Netcom Online Communications Services (408-241-9760 login: guest)
  10. Apparently-To: comp-std-c++@uunet.uu.net
  11. X-Auth: PGPMoose V1.1 PGP comp.std.c++
  12.     iQBFAgUBMVzQOuEDnX0m9pzZAQG43gF6Aj7N03tqO/NFNt1gaIcKWpK7lAlBkaxW
  13.     Rw9Sv2PLpHsl+D8x9d9ikjZpkm9hEaBn
  14.     =Vwnm
  15.  
  16. In Santa Cruz we decided to change the auto_ptr copy semantics to
  17. allow returns of auto_ptr from functions.  Following is a simple
  18. implementation.  It (almost) compiles with the latest Edison Design
  19. Group front end (the template friend declaration choked it).  Note
  20. that on most architectures the owner bit can be overlayed with the
  21. pointer for a smaller footprint, but the following is portable.
  22.  
  23. template<class X>
  24.    class auto_ptr {
  25.       mutable bool owner;
  26.       X* px;
  27.       template<class Y> friend class auto_ptr;
  28.    public:
  29.       explicit auto_ptr(X* p=0) 
  30.          : owner(p), px(p) {}
  31.       template<class Y>
  32.          auto_ptr(const auto_ptr<Y>& r) 
  33.             : owner(r.owner), px(r.release()) {}
  34.       template<class Y>
  35.          auto_ptr& operator=(const auto_ptr<Y>& r) {
  36.             if ((void*)&r != (void*)this) {
  37.                if (owner) 
  38.                   delete px;
  39.                owner = r.owner; 
  40.                px = r.release();
  41.             }
  42.             return *this;
  43.          }
  44.       ~auto_ptr()           { if (owner) delete px; }
  45.       X& operator*()  const { return *px; }
  46.       X* operator->() const { return px; }
  47.       X* get()        const { return px; }
  48.       X* release()    const { owner = 0; return px; }
  49.    };
  50.  
  51. ---
  52. [ comp.std.c++ is moderated.  To submit articles: try just posting with      ]
  53. [ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu         ]
  54. [ FAQ:      http://reality.sgi.com/employees/austern_mti/std-c++/faq.html    ]
  55. [ Policy:   http://reality.sgi.com/employees/austern_mti/std-c++/policy.html ]
  56. [ Comments? mailto:std-c++-request@ncar.ucar.edu                             ]
  57.